
#import "EAGLView.h"
#import <AudioToolbox/AudioServices.h>

@implementation EAGLView

@synthesize animating;
@dynamic animationFrameInterval;

// You must implement this method
+ (Class) layerClass
{
    return [CAEAGLLayer class];
}

- (id) initWithFrame:(CGRect)frame
{    
    self = [super initWithFrame:frame];
    return self;
}

- (void) setup:(float)contentScale inputScale:(float)inputScale
{
    // Get the layer
    CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
    
    eaglLayer.opaque = TRUE;
    eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
    
    eaglLayer.contentsScale = contentScale;
    
    animating = FALSE;
    displayLinkSupported = FALSE;
    animationFrameInterval = 1;
    displayLink = nil;
    animationTimer = nil;
    
    app = [[Application alloc] initApp];
    
    // A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer
    // class is used as fallback when it isn't available.
    NSString *reqSysVer = @"3.1";
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
        displayLinkSupported = TRUE;
    
    // the standard size in screen resolution multiplied by the content scale that depends on the pixel resolution
    app->appHeight = 480 * eaglLayer.contentsScale;
    app->appWidth = 320 * eaglLayer.contentsScale;

    app->contentScale = contentScale;
    app->inputScale = inputScale;
    
    [app setup];
}

- (void) mainLoop:(id)sender
{
    if(!animating)
        return;
    
	float dt;
	
	if (displayLinkSupported)
		dt = [displayLink duration];
	else
		dt = [animationTimer timeInterval];

	[app update: dt];

	[app render];
}

- (void) layoutSubviews
{
	[app resizeFromLayer:(CAEAGLLayer*)self.layer];
	[self addSubview:app];
    [self mainLoop:nil];
}

- (NSInteger) animationFrameInterval
{
	return animationFrameInterval;
}

- (void) setAnimationFrameInterval:(NSInteger)frameInterval
{
	// Frame interval defines how many display frames must pass between each time the
	// display link fires. The display link will only fire 30 times a second when the
	// frame internal is two on a display that refreshes 60 times a second. The default
	// frame interval setting of one will fire 60 times a second when the display refreshes
	// at 60 times a second. A frame interval setting of less than one results in undefined
	// behavior.
	if (frameInterval >= 1)
	{
		animationFrameInterval = frameInterval;
		
		if (animating)
		{
			[self stopAnimation];
			[self startAnimation];
		}
	}
}

- (void) startAnimation
{
	if (!animating)
	{
		if (displayLinkSupported)
		{
			// CADisplayLink is API new to iPhone SDK 3.1. Compiling against earlier versions will result in a warning, but can be dismissed
			// if the system version runtime check for CADisplayLink exists in -initWithCoder:. The runtime check ensures this code will
			// not be called in system versions earlier than 3.1.

			displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(mainLoop:)];
			[displayLink setFrameInterval:animationFrameInterval];
			[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
		}
		else
			animationTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)((1.0 / 60.0) * animationFrameInterval) target:self selector:@selector(mainLoop:) userInfo:nil repeats:TRUE];
		
		animating = TRUE;
	}
    
    [app startAcceleration];
}

- (void)stopAnimation
{
    [self saveState];
    
    [app minimize];
    
	if (animating)
	{
		if (displayLinkSupported)
		{
			[displayLink invalidate];
			displayLink = nil;
		}
		else
		{
			[animationTimer invalidate];
			animationTimer = nil;
		}
		
		animating = FALSE;
	}

    [app stopAcceleration];
}

- (void) saveState
{
    [app saveState];
}

- (void) loadState
{
    [app loadState];
}

- (void) dealloc
{
    [app release];
	
    [super dealloc];
}

// Handles the start of a touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	CGRect				bounds = [self bounds];
    UITouch*	touch = [[event touchesForView:self] anyObject];
	
	//Convert touch point from UIView referential to OpenGL one (upside-down flip)
	CGPoint location = [touch locationInView:self];
	location.y = bounds.size.height - location.y;
	
	[app touchStart:location];
}

// Handles the end of a touch event when the touch is a tap.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	CGRect				bounds = [self bounds];
    UITouch*	touch = [[event touchesForView:self] anyObject];
	
	CGPoint location = [touch previousLocationInView:self];
	location.y = bounds.size.height - location.y;
	
	[app touchEnd:location];
}

// Handles the continuation of a touch.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{  
	
	CGRect				bounds = [self bounds];
	UITouch*			touch = [[event touchesForView:self] anyObject];
	
	//Convert touch point from UIView referential to OpenGL one (upside-down flip)
	CGPoint	location = [touch locationInView:self];
	location.y = bounds.size.height - location.y;
    
	// Render the stroke
	[app touchMoved:location];
}

@end
